package cur.nature.component.quartz.config;

import cur.nature.component.quartz.model.Component_QuartzLogVO;
import cur.nature.component.quartz.service.Component_QuartzLogService;
import cur.nature.framework.core.log.LOG;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author wujian
 * @date 2021/08/28
 */
@Component
@Order(value = 1)
@ConditionalOnProperty( value = {"cur.component.quartz.enable"})
public class QuartzJobListener implements JobListener {

    @Autowired
    private Component_QuartzLogService quartzLogService;

    @Override
    public String getName() {
        return "scheduleJobListener";
    }

    @Override
    public void jobToBeExecuted(JobExecutionContext context) {
        LOG.info("执行scheduleJobListener: jobToBeExecuted");
        try {
            String jobCode = context.getJobDetail().getKey().getName();
            String jobGroup = context.getJobDetail().getKey().getGroup();
            Date fireTime = context.getFireTime();
            final Component_QuartzLogVO vo = quartzLogService.insertCust(jobGroup, jobCode,fireTime, -1, "开始执行");
            context.getMergedJobDataMap().put("logVO", vo);
        } catch (Exception e) {
            LOG.error("插入日志异常:", e);
        }
    }

    @Override
    public void jobExecutionVetoed(JobExecutionContext context) {
        LOG.info("执行scheduleJobListener: jobExecutionVetoed");
        try {
            final Component_QuartzLogVO vo = (Component_QuartzLogVO) context.getMergedJobDataMap().get("logVO");
            quartzLogService.updateCust(vo, 0, "任务被拒绝。");
        } catch (Exception e) {
            LOG.error("插入日志异常:", e);
        }
    }

    @Override
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
        //可以在此实现发邮件，短信提醒
        LOG.info("执行scheduleJobListener: jobWasExecuted");
        try {
            final Component_QuartzLogVO vo = (Component_QuartzLogVO) context.getMergedJobDataMap().get("logVO");
            String msg = "执行成功";
            int state = 1;
            if (jobException != null) {
                state = 0;
                msg = jobException.getMessage();
            }
            quartzLogService.updateCust(vo, state, msg);
        } catch (Exception e) {
            LOG.error("插入日志异常:", e);
        }
    }
}
